﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Fadada.FASC.SDK.DotNetCore.Interfaces;
using Fadada.FASC.SDK.DotNetCore.Model;
using Fadada.FASC.SDK.DotNetCore.Utils;
using Newtonsoft.Json;

namespace Fadada.FASC.SDK.DotNetCore.Services
{
    public class GetFromBodyService : IGetFromBodyService
    {
        public async Task<string> GetFromHttpBodyAsync(BaseInputInfo inputInfo, Dictionary<string, string> body, string token)
        {
            string strTimeStamp = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000).ToString();//毫秒值
            string strGUID = Guid.NewGuid().ToString("N");
            Dictionary<string, string> headerParames = new Dictionary<string, string>();//参数摘要计算得map
            headerParames.Add("X-FASC-App-Id", inputInfo.APP_ID);
            headerParames.Add("X-FASC-Sign-Type", "HMAC-SHA256");
            headerParames.Add("X-FASC-Timestamp", strTimeStamp);
            headerParames.Add("X-FASC-Nonce", strGUID);
            headerParames.Add("X-FASC-AccessToken", token);
            headerParames.Add("bizContent", body["bizContent"]);
            string strSign = SignUtil.GetSign(headerParames, strTimeStamp, inputInfo.APP_SECRET);

            headerParames.Add("X-FASC-Sign", strSign);
            var client = HttpWebHelp.CreateDefault(inputInfo.ReqDomainName + inputInfo.ReqEndPoint);
            headerParames.Remove("bizContent");
            foreach (var p in headerParames)
            {
                client.Headers[p.Key] = p.Value;
            }
            client.Method = inputInfo.ReqMethod;
            client.ContentType = "application/x-www-form-urlencoded";
            string bodyParam = "bizContent=" + HttpUtility.UrlEncode(body["bizContent"]);
            byte[] paramBytes = Encoding.UTF8.GetBytes(bodyParam);
            client.ContentLength = paramBytes.Length;
            using (Stream reqStream = client.GetRequestStream())
            {
                reqStream.Write(paramBytes, 0, paramBytes.Length);
            }

            var rspResponse = await Task.Run(() => client.GetResponseIgnoreServerError());
            var rspStr = rspResponse.GetResponseString();
            return rspStr;
        }
        public static string EncodeNonAsciiCharacters(string value)
        {
            StringBuilder sb = new StringBuilder();
            foreach (char c in value)
            {
                if (c > 127)
                {
                    // This character is too big for ASCII
                    string encodedValue = "\\u" + ((int)c).ToString("x4");
                    sb.Append(encodedValue);
                }
                else
                {
                    sb.Append(c);
                }
            }
            return sb.ToString();
        }
    }
}